package com.example.shop.es.dto;

import lombok.Data;
import lombok.NonNull;
import lombok.experimental.Accessors;
import org.checkerframework.checker.units.qual.C;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.SourceFilter;

import java.util.stream.Collectors;

@Data
@Accessors(chain = true)
public class ElasticSearchQueryParam {
    @NonNull
    /**
     * 查询条件
     */
    private QueryBuilder queryBuilder;
    /**
     * 分页。默认不分页
     */
    private Pageable pageable;
    /**
     * 指定只显示的字段。默认是全显示
     */
    private String[] fields;
    /**
     * 过滤指定的字段，默认是不过滤
     */
    private SourceFilter sourceFilter;
    /**
     * 排序规则
     */
    private Sort sort;
    /**
     * 高亮处理，必须得是字符串类型的字段，否则是不会进行高亮处理的
     */
    private HighlightQuery highlightQuery;



    private ElasticSearchQueryParam(QueryBuilder queryBuilder){
        this.queryBuilder = queryBuilder;
    }
    public static Builder builder(QueryBuilder queryBuilder){
        return new Builder(queryBuilder);
    }

    public static class Builder{
        private ElasticSearchQueryParam queryParam;
        public Builder(QueryBuilder queryBuilder){
            queryParam = new ElasticSearchQueryParam(queryBuilder);
        }

        public ElasticSearchQueryParam build(){
            return queryParam;
        }

        public Builder setQueryBuilder(QueryBuilder queryBuilder) {
            queryParam.queryBuilder = queryBuilder;
            return this;
        }

        public Builder setPageable(Pageable pageable) {
            queryParam.pageable = pageable;
            return this;
        }

        public Builder setFields(String[] fields) {
            queryParam.fields = fields;
            return this;
        }

        public Builder setSourceFilter(SourceFilter sourceFilter) {
            queryParam.sourceFilter = sourceFilter;
            return this;
        }

        public Builder setSort(Sort sort) {
            queryParam.sort = sort;
            return this;
        }

        public Builder setHighlight(HighlightBuilder highlight) {
            if(highlight!=null){
                queryParam.highlightQuery = new CustomHighlightQuery(highlight);
            }
            return this;
        }
    }
}
